package vip.redme.memory.service.impl;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.util.StrUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import vip.redme.memory.context.UserContext;
import vip.redme.memory.exception.BizException;
import vip.redme.memory.pojo.entity.Plan;
import vip.redme.memory.pojo.vo.PlanSaveVo;
import vip.redme.memory.repository.PlanRepository;
import vip.redme.memory.response.BaseResultCode;
import vip.redme.memory.service.PlanManageService;

import java.util.Collections;
import java.util.List;
import java.util.Optional;

/**
 * PlanManageServiceImpl
 *
 * @author HUZHAOYANG
 * @version 1.0
 * @date 2021/8/31 11:46
 */
@Transactional
@Slf4j
@Service
public class PlanManageServiceImpl implements PlanManageService {

    private static final String planPeriodFormat = "大约：{}{}";
    private static final String HOUR = "小时";
    private static final String DAY = "天";
    private static final String MONTH = "月";
    private static final String YEAR = "年";

    @Autowired
    private PlanRepository planRepository;

    /**
     * 创建Plan
     *
     * @param planSaveVo
     * @return void
     * @author HUZHAOYANG
     * @date 2021/8/31 14:02
     **/
    @Override
    public void createPlan(PlanSaveVo planSaveVo) {

        Plan plan = BeanUtil.toBean(planSaveVo, Plan.class);
        plan.setTotalTimes(planSaveVo.getSchedule().size());
        int totalHours = planSaveVo.getSchedule().stream().reduce(Integer::sum)
                                   .orElseThrow(() -> new BizException(BaseResultCode.ARGS_ILLEGAL));
        String planPeriod;
        if (totalHours < 24) {
            planPeriod = StrUtil.format(planPeriodFormat, totalHours, HOUR);
        } else if (totalHours < 24 * 30) {
            planPeriod = StrUtil.format(planPeriodFormat, totalHours / 24 + 1, DAY);
        } else if (totalHours < 24 * 30 * 12) {
            planPeriod = StrUtil.format(planPeriodFormat, totalHours / (24 * 30) + 1, MONTH);
        } else {
            planPeriod = StrUtil.format(planPeriodFormat, totalHours / (24 * 30 * 12) + 1, YEAR);
        }
        plan.setPlanPeriod(planPeriod);
        plan.setUserId(UserContext.getUserId());
        planRepository.saveAndFlush(plan);
    }

    /**
     * 查询所有Plan
     *
     * @return java.util.List<vip.redme.memory.pojo.entity.Plan>
     * @author HUZHAOYANG
     * @date 2021/9/1 16:16
     **/
    @Override
    public List<Plan> getAll() {
        List<Plan> plans = Optional.ofNullable(planRepository.findByUserId(UserContext.getUserId()))
                                   .orElse(Collections.emptyList());

        return plans;
    }
}
